import React, { useState, useEffect } from "react";
import { Form, Input, Button, message } from 'antd'
import { SettingApi } from "@/api/setting";
import { MailApi } from "@/api/mail";
interface IProps {
  settings: any;
}
const SMTPSetting: React.FC<IProps> = ({ settings }) => {
  const [smtpHost, setsmtpHost] = useState(null);
  const [smtpPort, setsmtpPort] = useState(null);
  const [smtpUser, setsmtpUser] = useState(null);
  const [smtpPass, setsmtpPass] = useState(null);
  const [smtpFromUser, setSmtpFromUser] = useState(null);
  const save = () => {
    SettingApi.updateSettings({
      smtpHost,
      smtpPort,
      smtpUser,
      smtpPass,
      smtpFromUser
    }).then(res => {
      message.success("保存成功")
    })
  }
  const sendMail = () => {
    MailApi.testSendMail(smtpUser).then(res => {
      message.success("邮箱发送成功")
    })
  }
  useEffect(() => {
    setsmtpHost(settings?.smtpHost || null)
    setsmtpPort(settings?.smtpPort || null)
    setsmtpUser(settings?.smtpUser || null)
    setsmtpPass(settings?.smtpPass || null)
    setSmtpFromUser(settings?.smtpFromUser || null)
  }, [settings])
  return (
    <Form>
      <Form.Item label="SMTP地址:">
        <Input value={smtpHost} onChange={e => setsmtpHost(e.target.value)} />
      </Form.Item>
      <Form.Item label="SMTP 端口（注意强制使用 SSL 连接）">
        <Input value={smtpPort} onChange={e => setsmtpPort(e.target.value)} />
      </Form.Item>
      <Form.Item label="SMTP 用户:">
        <Input value={smtpUser} onChange={e => setsmtpUser(e.target.value)} />
      </Form.Item>
      <Form.Item label="SMTP 密码:">
        <Input value={smtpPass} onChange={e => setsmtpPass(e.target.value)} placeholder={"也可能是授权码"} />
      </Form.Item>
      <Form.Item label="发件人:">
        <Input value={smtpFromUser} onChange={e => setSmtpFromUser(e.target.value)} />
      </Form.Item>
      <Form.Item>
        <Button type="primary" onClick={save}>保存</Button>
        <Button style={{marginLeft: 15}} onClick={sendMail}>测试</Button>
      </Form.Item>
    </Form>
  );
};

export default SMTPSetting;
